import React, {PureComponent} from 'react';
import { UploadOutlined } from '@ant-design/icons';
import {Button, Input, message, Space, Upload} from 'antd';
import api from '../../services/api'
import store from "store";
const {createUserAvatar} = api


export default class UploadEditor extends PureComponent {

  state = {val: ""}

  constructor(props) {
    super(props);
    this.state = {val: this.props.value};
  }

  onInputChange = function (e) {
    this.onChangeVal(e.target.value)
  }

  onChangeVal(v) {
    this.setState({val: v})
    this.props.onChange(v)
  }

  onFileChange = (info) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
      console.log(info)
      this.onChangeVal(info.file.response.payload)
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  }

  uploadProps = {
    p: this,
    name: 'avatar',
    action: createUserAvatar,
    headers: {
      Authorization:store.get('token'),
    },
    onChange: this.onFileChange,
    showUploadList: false,
  };

  render() {
    return <Space direction="horizontal">
      <Input defaultValue={this.state.val} value={this.state.val}  onChange={this.onInputChange.bind(this)} ref={(c)=>{this.input = c} } />
      <Upload {...this.uploadProps}>
        <Button icon={<UploadOutlined />}>Upload</Button>
      </Upload>
    </Space>
  }
}
